package org.study.mongo.boot.repository;

import com.mongodb.client.result.DeleteResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.study.mongo.boot.domain.Employee;

import java.util.Collection;
import java.util.List;

/**
 * @author Administrator
 * @date 2021-05-21
 */
@Slf4j
@Repository
public class MongoRepository {
    @Resource
    private MongoTemplate mongoTemplate;

    public void dropCollectionByClass() {
        boolean exists = mongoTemplate.collectionExists(Employee.class);
        log.info("集合是否存在：{}" + exists);
        if (exists) {
            mongoTemplate.dropCollection(Employee.class);
        }
    }

    public void dropCollection(String collectionName) {
        boolean exists = mongoTemplate.collectionExists(collectionName);
        log.info("集合是否存在：{}" + exists);
        if (exists) {
            mongoTemplate.dropCollection(collectionName);
        }
    }

    public Employee insertOne(Employee employee) {
        Employee insert = mongoTemplate.insert(employee);
        return insert;
    }

    public Collection<Employee> insertAll(List<Employee> list) {
        Collection<Employee> insertAll = mongoTemplate.insertAll(list);
        return insertAll;
    }

    public Employee save(Employee employee) {
        Employee save = mongoTemplate.save(employee);
        return save;
    }

    public Employee findById(String id) {
        Employee employee = mongoTemplate.findById(id, Employee.class);
        return employee;
    }

    public Employee findByName(String name) {
        Criteria c = new Criteria();
        c.and("name").is(name);
        Query query = new Query(c);
        Employee employee = mongoTemplate.findOne(query, Employee.class);
        return employee;
    }

    public List<Employee> findAll() {
        List<Employee> list = mongoTemplate.findAll(Employee.class);
        return list;
    }

    public DeleteResult deleteById(String id) {
        Criteria c = new Criteria();
        c.and("_id").is(id);
        Query query = new Query(c);
        DeleteResult deleteResult = mongoTemplate.remove(query, Employee.class);
        return deleteResult;
    }

    public DeleteResult deleteByName(String name) {
        Criteria c = new Criteria();
        c.and("name").is(name);
        Query query = new Query(c);
        DeleteResult deleteResult = mongoTemplate.remove(query, Employee.class);
        return deleteResult;
    }
}
